<!--
 * @Author: Charsen
 * @Date: 2025-07-18 17:43
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 14:26:40
 * @Description: 
-->
<template>
  <el-dialog
    :model-value="visible"
    :before-close="confirmClose"
    :close-on-click-modal="false"
    :title="title"
    :width="formWidth"
    :append-to-body="appendToBody"
    :destroy-on-close="true"
  >
    <div class="creator-form">
      <Former
        v-loading="loading"
        :data="createFormer.data"
        :fields="createFormer.fields"
        :loading="formLoading"
        :validate="createFormer.validate"
        @on-confirmed="onConfirmed"
        @on-closed="closeDialog"
      />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
  import { useCreator } from '#/hooks/useCreator'
  import { ElMessageBox } from 'element-plus'

  defineOptions({
    name: 'Creator',
  })

  const props = withDefaults(
    defineProps<{
      appendToBody?: boolean
      entity?: string
      formSize?: string
      message?: string
      requestUrl?: RequestUrl
      title?: string
      visible?: boolean
    }>(),
    {
      title: '添加',
      visible: false,
      appendToBody: false,
      requestUrl: () => ({}),
      formSize: 'normal',
      message: '添加成功',
      entity: '',
    }
  )

  const emits = defineEmits<{
    (e: 'update:visible', visible: boolean): void
    (e: 'on-stored', res: object): void
  }>()

  const { visible } = toRefs(props)

  const formWidth = computed(() => {
    const width = { large: '70vw', normal: '50vw', mini: '38vw' }
    return width[props.formSize as 'large' | 'mini' | 'normal']
  })

  const {
    loading,
    formLoading,
    createFormer,
    getCreateForm,
    getCreateFormWith,
    handleStore,
    handleStoreWith,
    resetCreator,
  } = useCreator({
    entity: props.entity,
    message: props.message,
  })

  const loadCreateForm = () => {
    return props.requestUrl.create ? getCreateFormWith(props.requestUrl) : getCreateForm()
  }

  watch(
    () => props.visible,
    (newV) => {
      if (newV) {
        loadCreateForm()
      }
    }
  )

  const onConfirmed = (form: object) => {
    const onStored = (res: any) => {
      emits('on-stored', res.data)
      closeDialog()
    }

    if (props.requestUrl?.store) {
      return handleStoreWith(
        {
          store: props.requestUrl.store as string,
          params: { ...props.requestUrl.params, ...form },
        },
        onStored
      )
    }

    return handleStore(form, onStored)
  }
  const closeDialog = () => {
    resetCreator()
    emits('update:visible', false)
  }

  const confirmClose = () => {
    ElMessageBox.confirm('确定关闭吗？', '温馨提示', { type: 'warning' })
      .then(() => {
        closeDialog()
      })
      .catch(() => {
        // catch error
      })
  }
</script>

<style lang="scss" scoped>
  .creator-form {
    @apply pt-20px pb-70px;
  }
</style>
